package atguigu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.sql.Connection;
import java.sql.SQLException;


/**
 *  自定义的数据库连接对的管理类
 *  类的功能：获取数据连接对象，释放资源
 *           管理事务，提交事务，回滚事务，开启事务
 *
 *  事务管理的核心和执行SQL语句的核心对象，Connection连接对象
 *  线程对象，和Connection对象进行绑定
 */

@Component
public class ConnectionManager {
    //定义ThreadLocal对象
    private ThreadLocal<Connection> local = new ThreadLocal<Connection>();
    //注入数据库连接池对象
    @Autowired
    private DruidDataSource dataSource;

    //释放资源
    public void close(){
        try {
            Connection con = getConnection();
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        local.remove();
    }

    //事物回滚
    public void rollback(){
        try {
            Connection con = getConnection();
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //事物提交
    public void commit()throws SQLException{
        Connection con = getConnection();
        con.commit();
    }
    //事物开启
    public void begin()throws SQLException{
        Connection con = getConnection();
        con.setAutoCommit(false);
    }


    //定义方法，返回数据库的连接对象
    public Connection getConnection() throws SQLException {
        //local对象中获取连接
        Connection con = local.get();
        //判断，有可能ThreadLocal中，没有存储过连接对象
        if (con == null){
            //从连接池中取出连接
            con = dataSource.getConnection();
            //连接对象，存储到ThreadLocal中
            local.set(con);
        }
        return con;
    }
}
